package org.darkforest.merchant.controller;

import org.darkforest.common.logger.Logger;
import org.darkforest.common.services.BoothGoodsService;
import org.darkforest.common.services.PMiaoShaService;
import org.darkforest.common.services.PXianShiService;
import org.darkforest.common.services.PXianshiGoodsService;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.util.Utils;
import org.darkforest.controller.WebController;
import org.darkforest.dao.mapper.GoodsMapper;
import org.darkforest.merchant.service.IGoodsService;
import org.darkforest.model.*;
import org.darkforest.ucenter.auth.AuthPassport;
import org.darkforest.vo.AjaxReturnData;
import org.darkforest.vo.AjaxReturnEntity;
import org.darkforest.vo.AjaxReturnImageVO;
import org.darkforest.vo.StoreSellerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * Created by valentina on 15/4/29.
 */
@Controller
@RequestMapping("promotion")
public class PromotionController extends WebController<PromotionController>{

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private PXianShiService pXianShiService;


    @Autowired
    private PXianshiGoodsService pXianshiGoodsService;


    @Autowired
    private PMiaoShaService pMiaoshaService;

    @Autowired
    private GoodsMapper goodsMapper;


    @Autowired
    private BoothGoodsService boothGoodsService;
    /**
     * 限时折扣列表 lb
     * @return
     */
    @RequestMapping("discount")
    public ModelAndView discount(@RequestParam(required = false, defaultValue = "") String xianshiName,
                                 @RequestParam(required = false, defaultValue = "1") String start,
                                 @RequestParam(required = false, defaultValue = "") String state,
                                 HttpServletRequest request){
        Integer storeId = ((StoreSellerVo) request.getSession().getAttribute("sellerInfo")).getStoreId();
        PXianshi pXianshiPage = new PXianshi();
        pXianshiPage.setStoreId(storeId);
        pXianshiPage.setStart(Integer.parseInt(start));
        pXianshiPage.setPageSize(5);
        if(!"".equals(state)){
            pXianshiPage.setState(Byte.parseByte(state));
        }
        pXianshiPage.setXianshiName(xianshiName);
        pXianshiPage = pXianShiService.findTimeLimitedBuyingActiveByPage(pXianshiPage);
        ModelAndView modelAndView = new ModelAndView("promotion/discount");
        modelAndView.addObject("pageBean",pXianshiPage);
        return modelAndView;
    }


    @RequestMapping("deleteXianshiActive")
    public @ResponseBody boolean deleteXianshiActive(Integer activeId){
        boolean flag = this.pXianShiService.deleteXianshiActiveByKey(activeId);
        return flag;
    }


    @RequestMapping("addDiscount")
    public ModelAndView discount_add(){
        return new ModelAndView("promotion/add_discount");
    }


    @RequestMapping("doAddDiscount")
    public ModelAndView doAddDiscount(HttpServletRequest request){
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        String xianshiName = request.getParameter("xianshiName");
        String xianshiTitle = request.getParameter("xianshiTitle");
        String xianshiExplain = request.getParameter("xianshiExplain");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String lowerLimit = request.getParameter("lowerLimit");

        PXianshi pXianshi = new PXianshi();
        pXianshi.setXianshiName(xianshiName);
        pXianshi.setXianshiTitle(xianshiTitle);
        pXianshi.setXianshiExplain(xianshiExplain);
        pXianshi.setStartTime(DateUtil.toUnixTimeStamp(startTime));
        pXianshi.setEndTime(DateUtil.toUnixTimeStamp(endTime));
        pXianshi.setLowerLimit(Integer.parseInt(lowerLimit));
        pXianshi.setMemberId(sellerVo.getMemberId());
        pXianshi.setMemberName(sellerVo.getMemberName());
        pXianshi.setStoreId(sellerVo.getStoreId());
        pXianshi.setQuotaId(0);
        pXianshi.setState((byte)0);
        pXianshi.setActiveState(1);
        pXianshi.setStoreName(sellerVo.getStoreName());
        pXianShiService.addPxianshiActive(pXianshi);
        return new ModelAndView("redirect:discount");
    }



    @RequestMapping("toManagerDiscount")
    public ModelAndView toManagerDiscount(Integer xianshiId){
        ModelAndView modelAndView = new ModelAndView("promotion/manage_discount");
        PXianshi pXianshi = this.pXianShiService.getPXianshiActiveByKey(xianshiId);
        PXianshiGoods pXianshiGoods =  new PXianshiGoods();
        pXianshiGoods.setXianshiId(xianshiId);
        List<PXianshiGoods> pXianshiGoodsList = this.pXianshiGoodsService.findPXianshiGoodsListByCondition(pXianshiGoods);
        modelAndView.addObject("pXianshi", pXianshi);
        modelAndView.addObject("pXianshiGoodsList",pXianshiGoodsList);
        return modelAndView;
    }


    @RequestMapping("toAddDiscountGoods")
    public ModelAndView toAddDiscountGoods(HttpServletRequest request,
                                           @RequestParam(required = false, defaultValue = "") String goodsName,
                                           @RequestParam(required = false, defaultValue = "1") String start
                                           ){
        ModelAndView modelAndView = new ModelAndView("promotion/discount_search_goods");
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");

        GoodSearchBean goodSearchBean = new GoodSearchBean();
        if(!org.apache.commons.lang.StringUtils.isEmpty(goodsName)){
            goodSearchBean.setGoodsName(Utils.encodeGetParam(goodsName));
        }
        goodSearchBean.setStoreId(sellerVo.getStoreId());
        goodSearchBean.setStart(Integer.parseInt(start));
        goodSearchBean.setGoodsType(0);
        goodSearchBean.setGoodsState(1);
        goodSearchBean.setGoodsVerify(1);
        this.goodsService.searchGoodsByPage(goodSearchBean);
        modelAndView.addObject("pageBean",goodSearchBean);
        return modelAndView;
    }


    @RequestMapping("doAddDiscountGoods")
    public @ResponseBody
    AjaxReturnEntity<PXianshiGoods> doAddDiscountGoods(Integer goods_id,Integer xianshi_id,float xianshi_price,String xinshi_jingo){
        AjaxReturnEntity<PXianshiGoods> ajaxReturnData = pXianshiGoodsService.doAddDiscountGoods(goods_id, xianshi_id, xianshi_price, xinshi_jingo);
        return ajaxReturnData;
    }

    @RequestMapping("deleteDiscountGoods")
    public @ResponseBody
    AjaxReturnEntity<PXianshiGoods> deleteDiscountGoods(Integer xianshi_goods_id){
        AjaxReturnEntity<PXianshiGoods> ajaxReturnData = pXianshiGoodsService.deleteDiscountGoods(xianshi_goods_id);

        return ajaxReturnData;
    }


    @RequestMapping("editDiscountGoods")
    public @ResponseBody
    AjaxReturnEntity<PXianshiGoods> editDiscountGoods(Integer xianshi_goods_id,float xianshi_price,String goods_jingo){
        AjaxReturnEntity<PXianshiGoods> ajaxReturnData = pXianshiGoodsService.editDiscountGoods(xianshi_goods_id, xianshi_price, goods_jingo);

        return ajaxReturnData;
    }


    /**
     * 活动管理
     * @return
     */
    @RequestMapping("activity")
    public String activity(){
        return "promotion/activity";
    }

    /**
     * 推荐展位
     * @return
     */
    @RequestMapping("recommend")
    public String recommend(
                            @RequestParam(required = false, defaultValue = "1") String start,HttpServletRequest request
                            ){
        Integer storeId = ((StoreSellerVo) request.getSession().getAttribute("sellerInfo")).getStoreId();
        PBoothGoods param =  new PBoothGoods();
        param.setStoreId(storeId);
        param.setStart(Integer.parseInt(start));
//        param.setBoothState((byte)1);
        PBoothGoods pBoothGoods = boothGoodsService.selectRecommondGoodsByPage(param);
        request.setAttribute("pageBean",pBoothGoods);
        return "promotion/recommend";
    }

    @RequestMapping(value = "modifyRecommend")
    @AuthPassport
    public @ResponseBody boolean modifyRecommend(PBoothGoods pBoothGoods){
        boothGoodsService.updateByPrimaryKeySelective(pBoothGoods);
        return true;
    }


    /**
     * 删除推荐展位
     * @param gid
     * @return
     */
    @RequestMapping("delRecommondGoods")
    public @ResponseBody AjaxReturnData delRecommondGoods(Integer gid){
        AjaxReturnData ajaxReturnData = this.boothGoodsService.delRecommondGoods(gid);

        return ajaxReturnData;
    }



    //#######################商品秒杀管理################

    /**
     * 秒杀商品列表
     * @param msActiveName
     * @param start
     * @param state
     * @return
     */
    @RequestMapping("miaoshaActivity")
    public ModelAndView miaoshaActivity(@RequestParam(required = false, defaultValue = "") String msActiveName,
                                     @RequestParam(required = false, defaultValue = "1") String start,
                                     @RequestParam(required = false, defaultValue = "") String state,
                                        HttpServletRequest request){
        PMiaosha pMiaosha = new PMiaosha();
        Integer storeId = ((StoreSellerVo) request.getSession().getAttribute("sellerInfo")).getStoreId();
        pMiaosha.setStoreId(storeId);
        pMiaosha.setStart(Integer.parseInt(start));
        pMiaosha.setPageSize(5);
        if(!"".equals(state)){
            pMiaosha.setState(Byte.parseByte(state));
        }
        pMiaosha.setMsName(msActiveName);
        pMiaosha = this.pMiaoshaService.findMiaoShaByPage(pMiaosha);

        ModelAndView modelAndView = new ModelAndView("promotion/miaosha_list");
        modelAndView.addObject("pageBean",pMiaosha);

        return modelAndView;

    }

    @RequestMapping("toModifyMiaosha")
    public ModelAndView toModifyMiaosha(Integer msId){
        ModelAndView modelAndView = new ModelAndView("promotion/miaosha_modify");
        PMiaosha pMiaosha = this.pMiaoshaService.findMiaoshaById(msId);
        modelAndView.addObject("miaosha",pMiaosha);
        return modelAndView;

    }


    @RequestMapping("doModifyMiaoshaActivity")
    public String doModifyMiaoshaActivity(HttpServletRequest request){
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");

        Integer startTime = DateUtil.toUnixTimeStamp(request.getParameter("startTime"));
        Integer msAmount = Integer.parseInt(request.getParameter("msAmount"));
        Integer endTIme = DateUtil.toUnixTimeStamp(request.getParameter("endTime"));
        Integer state = 1;
//        Integer maxLimit =Integer.parseInt(request.getParameter("maxLimit"));
        Integer maxLimit=1;
        BigDecimal msPrice = new BigDecimal(request.getParameter("msPrice"));
        String msQuestion = request.getParameter("msQuestion");
        String msExplain = request.getParameter("msExplain");
        String msAnswer = request.getParameter("msAnswer");
        Integer msId = Integer.parseInt(request.getParameter("msId"));
        String msActiveImage = request.getParameter("msActiveImage");

        int quotaId = 0;
        String msName = request.getParameter("msName");
        String msTitle = request.getParameter("msTitle");

        PMiaosha pMiaosha = new PMiaosha();
        pMiaosha.setMsId(msId);
        pMiaosha.setMsName(msName);
        pMiaosha.setMsTitle(msTitle);
        pMiaosha.setMsExplain(msExplain);
        pMiaosha.setQuotaId(quotaId);
        pMiaosha.setStartTime(startTime);
        pMiaosha.setEndTime(endTIme);
        pMiaosha.setMemberId(sellerVo.getMemberId());
        pMiaosha.setStoreId(sellerVo.getStoreId());
        pMiaosha.setMemberName(sellerVo.getMemberName());
        pMiaosha.setStoreName(sellerVo.getStoreName());
        pMiaosha.setMaxLimit(maxLimit.byteValue());
        pMiaosha.setMsAmount(msAmount);
        pMiaosha.setMsQuestion(msQuestion);
        pMiaosha.setMsAnswer(msAnswer);
        pMiaosha.setMsPrice(msPrice);
        pMiaosha.setState(state.byteValue());
        pMiaosha.setMsActiveImage(msActiveImage);

        pMiaoshaService.updateSelectActive(pMiaosha);
        return "redirect:miaoshaActivity";
    }


    /**
     * 秒杀商品列表
     * @param goodsName
     * @param start
     * @return
     */
    @RequestMapping(value = "chooseMiaoshaGoods")
    public ModelAndView chooseMiaoshaGoods(HttpServletRequest request,
                                           @RequestParam(required = false, defaultValue = "") String goodsName,
                                           @RequestParam(required = false, defaultValue = "1") String start){
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        ModelAndView modelAndView = new ModelAndView("promotion/miaosha_search_goods");
        GoodSearchBean goodSearchBean = new GoodSearchBean();
        Logger.debug(PromotionController.class, "=========goodsName:" + goodsName + "," + Utils.encodeGetParam(goodsName));
        goodSearchBean.setGoodsName(Utils.encodeGetParam(goodsName));
        goodSearchBean.setStart(Integer.parseInt(start));
        goodSearchBean.setStoreId(sellerVo.getStoreId());
        goodSearchBean.setGoodsType(0);
        goodSearchBean.setGoodsState(1);
        goodSearchBean.setGoodsVerify(1);
        this.goodsService.searchGoodsByPage(goodSearchBean);
        modelAndView.addObject("pageBean",goodSearchBean);
        return modelAndView;
    }

    /**
     * 选择推荐商品列表
     * @param goodsName
     * @param start
     * @return
     */
    @RequestMapping(value = "chooseRecommondGoods")
    public ModelAndView chooseRecommondGoods(HttpServletRequest request,
                                           @RequestParam(required = false, defaultValue = "") String goodsName,
                                           @RequestParam(required = false, defaultValue = "1") String start){
        ModelAndView modelAndView = new ModelAndView("promotion/recommend_search_goods");
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");


        GoodsCommonSearchBean goodSearchBean = new GoodsCommonSearchBean();
        Logger.debug(PromotionController.class,"=========goodsName:"+goodsName+","+Utils.encodeGetParam(goodsName));
        goodSearchBean.setGoodsName(Utils.encodeGetParam(goodsName));
        goodSearchBean.setStoreId(sellerVo.getStoreId());
        goodSearchBean.setStart(Integer.parseInt(start));
        goodSearchBean.setGoodsType(0);
        goodSearchBean.setInStatus("(1)");
        goodSearchBean.setGoodsVerify(1);
        this.goodsService.findGoodsInState(goodSearchBean);

        modelAndView.addObject("pageBean",goodSearchBean);
        return modelAndView;
    }


    @RequestMapping("doAddRecommondGoods")
    public @ResponseBody
    AjaxReturnData doAddRecommondGoods(Integer goods_id,Integer recommondType,Integer sort,HttpServletRequest request) throws Exception {
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");

        AjaxReturnData ajaxReturnData = boothGoodsService.addRecommondGoods(goods_id,recommondType,sort,sellerVo.getStoreId());

        return ajaxReturnData;
    }


    /**
     * 为秒杀活动选择商品
     * @return
     */
    @RequestMapping("selectGoodsToMS")
    public @ResponseBody Goods selectMiaoShaGoods(Integer goodsId){
        Goods goods = goodsMapper.getGoodsById(goodsId);
        return goods;
    }

    /**
     * 跳转到新增秒杀活动页面
     * @return
     */
    @RequestMapping("toAddMiaoSha")
    public ModelAndView toAddMiaoSha(){
        ModelAndView modelAndView = new ModelAndView("promotion/miaosha_add");
        return modelAndView;
    }

    /**
     * 执行添加秒杀活动
     * @return
     */
    @RequestMapping(value = "doAddMiaoSha",method = RequestMethod.POST)
    public String doAddMiaoSha(HttpServletRequest request){
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");

        Integer goodsId = Integer.parseInt(request.getParameter("goodsId"));
        Integer startTime = DateUtil.toUnixTimeStamp(request.getParameter("startTime"));
        Integer msAmount = Integer.parseInt(request.getParameter("msAmount"));
        Integer endTIme = DateUtil.toUnixTimeStamp(request.getParameter("endTime"));
        Integer state = 1;
//        Integer maxLimit =Integer.parseInt(request.getParameter("maxLimit"));
        Integer maxLimit=1;
        BigDecimal goodsPrice = new BigDecimal(request.getParameter("goodsPrice"));
        BigDecimal msPrice = new BigDecimal(request.getParameter("msPrice"));
        String goodsName = request.getParameter("goodsName");
        String goodsImage =request.getParameter("goodsImage");
        String msQuestion = request.getParameter("msQuestion");
        String msExplain = request.getParameter("msExplain");
        String msAnswer = request.getParameter("msAnswer");
        String msActiveImage = request.getParameter("msActiveImage");

        int quotaId = 0;
        String msName = request.getParameter("msName");
        String msTitle = request.getParameter("msTitle");
        PMiaosha pMiaosha = new PMiaosha();
        pMiaosha.setMsName(msName);
        pMiaosha.setMsTitle(msTitle);
        pMiaosha.setMsExplain(msExplain);
        pMiaosha.setQuotaId(quotaId);
        pMiaosha.setStartTime(startTime);
        pMiaosha.setEndTime(endTIme);
        pMiaosha.setMemberId(sellerVo.getMemberId());
        pMiaosha.setStoreId(sellerVo.getStoreId());
        pMiaosha.setMemberName(sellerVo.getMemberName());
        pMiaosha.setStoreName(sellerVo.getStoreName());
        pMiaosha.setMaxLimit(maxLimit.byteValue());
        pMiaosha.setMsAmount(msAmount);
        pMiaosha.setMsQuestion(msQuestion);
        pMiaosha.setMsAnswer(msAnswer);
        pMiaosha.setGoodsId(goodsId);
        pMiaosha.setGoodsName(goodsName);
        pMiaosha.setMsPrice(msPrice);
        pMiaosha.setGoodsImage(goodsImage);
        pMiaosha.setState(state.byteValue());
        pMiaosha.setGoodsPrice(goodsPrice);
        pMiaosha.setMsActiveImage(msActiveImage);
        int res = this.pMiaoshaService.addPMiaoSha(pMiaosha);
        LOGGER.debug("保存秒杀："+res);
//        miaoshaActivity(null,"1",null);
        return "redirect:miaoshaActivity";
    }


    @RequestMapping("checkMSAcitive")
    public @ResponseBody boolean checkMSAcitive(HttpServletRequest request){
        Integer startTime = DateUtil.toUnixTimeStamp(request.getParameter("startTime"));
        Integer goodsId = Integer.parseInt(request.getParameter("goodsId"));
        boolean flag = this.pMiaoshaService.checkMSAcitive(startTime,goodsId);

        return flag;
    }


    @RequestMapping("uploadMSActiveImg")
    public @ResponseBody AjaxReturnImageVO uploadMSActiveImg(MultipartHttpServletRequest multipartHttpServletRequest){
        AjaxReturnImageVO ajaxReturnData = new AjaxReturnImageVO();
        try {
            MultipartFile activeImageFile = multipartHttpServletRequest.getFile("groupbuy_image");

            String  activeImage = super.uploadPicsWithoutCompressSize(activeImageFile, multipartHttpServletRequest, null, null);

            ajaxReturnData.setAjaxMsg("秒杀活动宣传图上传成功");
            ajaxReturnData.setReturnCode("true");
            ajaxReturnData.setImageName(activeImage);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ajaxReturnData;
    }


    @RequestMapping("uploadZKActiveImg")
    public @ResponseBody AjaxReturnImageVO uploadZKActiveImg(MultipartHttpServletRequest multipartHttpServletRequest){
        AjaxReturnImageVO ajaxReturnData = new AjaxReturnImageVO();
        String pxianshiGoodsId = multipartHttpServletRequest.getParameter("pxianshiGoodsId");
        String xianshiId = multipartHttpServletRequest.getParameter("xianshiId");

        try {
            MultipartFile activeImageFile = multipartHttpServletRequest.getFile("groupbuy_image");

            String  activeImage = super.uploadPicsWithoutCompressSize(activeImageFile, multipartHttpServletRequest, null, null);


            this.pXianshiGoodsService.modifyPXianShiGoodsToUploadImage(pxianshiGoodsId,xianshiId,activeImage);
            ajaxReturnData.setAjaxMsg("限时折扣活动宣传图上传成功");
            ajaxReturnData.setReturnCode("true");
            ajaxReturnData.setImageName(activeImage);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ajaxReturnData;
    }


}
